﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using DAL;
using System.Reflection;
using System.Collections;
using Facade.Excel;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;

namespace PeisongWeb.admin
{
    public partial class receivablesList : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("GB", 1))
                {
                    drpBind();
                    rptBind();
                    showCollect();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
                
            }
        }
        void drpBind()
        {
            ddl_Type.DataSource = logic.sysCode.listWithPayStatus("1");
            ddl_Type.DataBind();
            ddl_Type.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));

            ddl_Paymethod.DataSource = logic.sysCode.payMethodList();
            ddl_Paymethod.DataBind();
            ddl_Paymethod.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }
        void rptBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("type='1'");
            if (txt_companyName.Text.Trim() != "")
                where.AppendFormat(" and companyName like '%{0}%'", txt_companyName.Text.Trim());
            if (txt_CompanyNo.Text.Trim() != "")
                where.AppendFormat(" and companyNo like '%{0}%'", txt_CompanyNo.Text.Trim());
            if (ddl_Type.SelectedValue != "")
                where.AppendFormat(" and status = '{0}'", ddl_Type.SelectedValue.Trim());
            if (ddl_Paymethod.SelectedValue != "")
                where.AppendFormat(" and payMethod = '{0}'", ddl_Paymethod.SelectedValue.Trim());

            if (ext_StartInputDt.SelectedDate != DateTime.MinValue && ext_StartInputDt.Value.ToString() != "")
                where.AppendFormat(" and datediff(day,[startDt],'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue && ext_EndInputDt.Value.ToString() != "")
                where.AppendFormat(" and datediff(day,[endDt],'{0}')>=0", ext_EndInputDt.Value.ToString());

            DataSet ds = logic.paymentHistory.select(where.ToString(), "payId desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Extend")
            {
                int payId = Convert.ToInt32(e.CommandArgument);
                hid_PayId.Value = payId.ToString();
                showExtendDay();
                win_Extend.Show();
            }
            else if (e.CommandName == "upadateStatus")
            {
                int payId = Convert.ToInt32(e.CommandArgument);

                PaymentHistoryEntity phe = new PaymentHistoryEntity();
                phe.AdminId = logic.sysAdmin.AdminID;
                phe.Status = "2"; //确认收款
                phe.PayId = payId;
                logic.paymentHistory.update(phe);

                rptBind();

                Library.Script.ClientMsg("已经成功更新！");
            }
            else if (e.CommandName == "Details")
            {
                AspNetPager2.CurrentPageIndex = 1;
                int payId = Convert.ToInt32(e.CommandArgument);
                PaymentHistoryEntity _phe = logic.paymentHistory.getByPayId(payId);
                hid_companyId.Value = _phe.CompanyId.ToString();
                hid_startDt.Value = _phe.StartDt.ToString();
                hid_endDt.Value = _phe.EndDt.ToString();
                hid_PayId.Value = payId.ToString();
                rptOrderItemBind(payId);
                orderItem.Show();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }
        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
            showCollect();
        }
        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            int payId = Convert.ToInt32(hid_PayId.Value);
            rptOrderItemBind(payId);
        }
        void rptOrderItemBind(int payId)
        {
            int company = Convert.ToInt32(hid_companyId.Value);
            string startDt = hid_startDt.Value;
            string  endDt = hid_endDt.Value;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("companyId={0} ", company);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", startDt);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", endDt);
            if (txt_orderNo.Text.Trim() != "")
                sb.AppendFormat("and orderno='{0}'",txt_orderNo.Text.Trim());
            DataSet ds = logic.orderItem.listWithOrder(sb.ToString(), "orderid", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_orderItem.DataSource = ds.Tables[1];
            rpt_orderItem.DataBind();
            rpt_orderItemBind();
        }

        protected void lbn_select_Click(object sender, EventArgs e)
        {
            int payId = Convert.ToInt32(hid_PayId.Value);
            rptOrderItemBind(payId);
        }

        private DataSet orderItemByWhere()
        {
            int company = Convert.ToInt32(hid_companyId.Value);
            string startDt = hid_startDt.Value;
            string endDt = hid_endDt.Value;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("companyId={0} ", company);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", startDt);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", endDt);
            if (txt_orderNo.Text.Trim() != "")
                sb.AppendFormat("and orderno='{0}'", txt_orderNo.Text.Trim());
            DataSet ds = logic.orderItem.listwithReceivables(sb.ToString());
            return ds;
        }

        protected void lbn_Import_Click(object sender, EventArgs e)
        {
            DataSet ds = orderItemByWhere();
            DataTable dt = ds.Tables[0];
            dt.Columns[0].ColumnName = "商品名称";
            dt.Columns[1].ColumnName = "数量";
            dt.Columns[2].ColumnName = "单价";
            dt.Columns[3].ColumnName = "单位";
            dt.Columns[4].ColumnName = "小计";
            dt.Columns[5].ColumnName = "订单号";
            dt.Columns[6].ColumnName = "订单状态";
            dt.Columns[7].ColumnName = "交易成功日期";
            dt.Columns[8].ColumnName = "收货日期";

            Dictionary<int, FormatStyle> formatOptions = new Dictionary<int, FormatStyle>();
            formatOptions.Add(1, FormatStyle.ToFix2);
            formatOptions.Add(2, FormatStyle.ToFix2);
            formatOptions.Add(4, FormatStyle.ToFix2);
            formatOptions.Add(7, FormatStyle.DateTime);

            List<int> footerSumColumns = new List<int>() { 4 };
            List<int> mergeColumnIndexs = new List<int>() { 5, 6, 7, 8 };

            string title = string.Format("{0} {1} 至 {2} 账期订单数据",logic.company.getById(Convert.ToInt32(hid_companyId.Value)).Company, hid_startDt.Value, hid_endDt.Value);

            ExportFacade facade = new ExportFacade();

            HSSFWorkbook workbook = facade.InitializeWorkbook("杭州农副产品物流网络科技有限公司", "tianzh", "采购配送系统", "财务账单订单数据");

            Sheet sheet1 = workbook.CreateSheet("订单详细");

            facade.CreateRowHeader(workbook, sheet1, title, dt);
            facade.FillRowData(workbook, sheet1, 2, dt, formatOptions, null, footerSumColumns, null);

            // 小类汇总
            DataTable dt2 = ds.Tables[2];
            dt2.Columns[0].ColumnName = "类别";
            dt2.Columns[1].ColumnName = "金额";

            int startRowIndex=2 + dt.Rows.Count + 1 + 5;

            #region 创建标题行

            Row titleRow = sheet1.CreateRow(startRowIndex);
            titleRow.HeightInPoints = 25;
            titleRow.CreateCell(0).SetCellValue("分类汇总信息");

            CellStyle titleStyle = workbook.CreateCellStyle();
            titleStyle.Alignment = HorizontalAlignment.CENTER;
            Font titleFont = workbook.CreateFont();
            titleFont.FontHeightInPoints = 20;
            titleFont.Boldweight = 700;
            titleStyle.SetFont(titleFont);
            titleStyle.WrapText = true;

            titleRow.GetCell(0).CellStyle = titleStyle;
            sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1));

            Row headerRow = sheet1.CreateRow(startRowIndex+1);

            CellStyle headStyle = workbook.CreateCellStyle();
            headStyle.Alignment = HorizontalAlignment.CENTER;
            Font font = workbook.CreateFont();
            font.FontHeightInPoints = 10;
            font.Boldweight = 700;
            headStyle.SetFont(font);

            foreach (DataColumn column in dt2.Columns)
            {
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
            }
            #endregion

            facade.FillRowData(workbook, sheet1, startRowIndex + 2, dt2, null, null, null, null);

            facade.ExportByWeb(workbook, title, title + ".xls");
        }

        private void showExtendDay()
        {
            int payId = Convert.ToInt32(hid_PayId.Value);
            DataRow dr = logic.paymentHistory.selectWithExtend("payid = "+payId, "payid", 1, 1).Tables[1].Rows[0];
            txt_ExtendDay.Text = dr["ExtendDay"].ToString();
        }
        protected void btn_save_ExtendDay_Click(object sender, EventArgs e)
        {
            PmtExtendSetEntity pmtEnt = new PmtExtendSetEntity();
            pmtEnt.PayId = Convert.ToInt32(hid_PayId.Value);
            pmtEnt.ExtendDay = Convert.ToInt32(txt_ExtendDay.Text);
            pmtEnt.Admin = logic.sysAdmin.AdminID;
            logic.pmtExtendSet.update(pmtEnt);
        }
        private void showCollect()
        {
            int companyId = 0;
            DateTime? startDt = null;
            DateTime? endDt = null;
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue) startDt = ext_StartInputDt.SelectedDate;
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue) endDt = ext_EndInputDt.SelectedDate;

            string companyName = txt_companyName.Text.Trim();
            string companyNo = txt_CompanyNo.Text.Trim();
            string paymethod = ddl_Paymethod.SelectedValue.Trim();

            DataRow dr = logic.paymentHistory.listWithCollectByFinancial(companyId, startDt, endDt,companyName,companyNo,paymethod,"1").Rows[0];

            lit_orderNum.Text = string.Format("{0:N}", dr["orderNum"]);
            lit_payMoney.Text = string.Format("{0:N}", dr["payMoney"]);
            lit_notPayMoney.Text = string.Format("{0:N}", dr["notPayMoney"]);
            lit_total.Text = string.Format("{0:N}", dr["orderAmount"]);
        }
        private void rpt_orderItemBind()
        {
            DataTable dt = orderItemByWhere().Tables[1];
            lbl_Total.Text = string.Format("{0:F2}",dt.Rows[0]["total"]);
        }
    }
}
